package bigdata.backend.mata.test;

import bigdata.backend.meta.dto.ColumnLineage;
import bigdata.backend.meta.dto.TableLineage;
import bigdata.backend.meta.utils.TableAndColumnLineage;
import net.sf.jsqlparser.JSQLParserException;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
public class TestTableAndColumnLineage {
    @Test
    public void test01() throws JSQLParserException {
        // table lineage
        String sql = "WITH position_tmp as ( SELECT * FROM realtime_ods.position_info ) INSERT OVERWRITE TABLE realtime_dwd.user_dim SELECT t1.id, t1.name, t2.name as position_name, '1' as status, current_timestamp() as update_time FROM ( SELECT * FROM ( SELECT id, sd_name as name, position_id from realtime_ods.user_info_sd UNION ALL SELECT id, ah_name as name, position_id from realtime_ods.user_info_ah ) a1 ) t1 LEFT JOIN ( SELECT id, concat(name, id) as name FROM position_tmp a1 WHERE a1.id <= 100 ) t2 ON t1.position_id = t2.id INNER JOIN ( SELECT a1.id FROM ( SELECT id FROM realtime_ods.position_info2 ) a1 GROUP BY a1.id ) t3 ON t1.id = t3.id ;";
        TableLineage tableLineage = TableAndColumnLineage.getTableLineage(sql);
        System.out.println(tableLineage);
    }

    @Test
    public void test02() throws Exception {
        String sql = "WITH position_tmp as ( SELECT * FROM realtime_ods.position_info ) INSERT OVERWRITE TABLE realtime_dwd.user_dim SELECT t1.id, t1.name, t2.name as position_name, '1' as status, current_timestamp() as update_time FROM ( SELECT * FROM ( SELECT id, sd_name as name, position_id from realtime_ods.user_info_sd UNION ALL SELECT id, ah_name as name, position_id from realtime_ods.user_info_ah ) a1 ) t1 LEFT JOIN ( SELECT id, concat(name, id) as name FROM position_tmp a1 WHERE a1.id <= 100 ) t2 ON t1.position_id = t2.id INNER JOIN ( SELECT a1.id FROM ( SELECT id FROM realtime_ods.position_info2 ) a1 GROUP BY a1.id ) t3 ON t1.id = t3.id ;";
        TableLineage tableLineage = TableAndColumnLineage.getTableLineage(sql);
        String targetTable = tableLineage.getTargetTable();
        List<ColumnLineage> columnLineages = TableAndColumnLineage.getColumnLineage(targetTable, sql);
        columnLineages.forEach((columnLineage) -> {
            System.out.println(columnLineage.getTargetColumn() + " <- " + columnLineage.getSourceColumns());
        });
    }
}
